(function(){
    var $$id=0;
    var modalTemplate=[];
    function getTemplate(str){
        for(var i=0;i<modalTemplate.length;i++){
            if(modalTemplate[i].key===str){
                return modalTemplate[i].value;
            }
        }
        return undefined;
    }
    //modal扩展
    $.extend({
        modal: {
            open: function (options) {
                if (!options.template) {
                    throw '$.modal() options.template is need!';
                }
                var str,
                    opendef= $.Deferred(),
                    resultdef= $.Deferred(),
                    position=[];
                var returnDef={
                    open:opendef.promise(),
                    result:resultdef.promise()
                }
                if(!(str=getTemplate(options.template))){
                    $.get(options.template,function(data){
                        str=data;
                        modalTemplate.push({key:options.template,value:str});
                        openEvents(str);
                    });
                }else{
                    openEvents(str);
                }
                return returnDef;

                function openEvents(str){
                    var modalDom = $(str);
                    modalDom.on('shown.bs.modal', function (e) {
                        !!options.controller&&options.controller(options.data);
                        setCenter(1);
                        if(options.canMove!==false){
                            setMove(1);
                        }
                        opendef.resolve('shown');
                    });
                    modalDom.on('hidden.bs.modal', function (e) {
                        $(e.currentTarget).remove();
                        resultdef.resolve('hidden');
                    });
                    $(document.body).append(modalDom);
                    modalDom.modal({backdrop:false,keyboard:false,show:true,});
                }
                function setCenter(length){
                    var clientHeight=$(".modal-dialog").eq(length-1).innerHeight(),
                        leftHeight=window.innerHeight-$(".modal-dialog").eq(length-1).innerHeight(),
                        leftWidth=window.innerWidth-$(".modal-dialog").eq(length-1).innerWidth();
                    var style={
                        height:clientHeight+"px",
                        top:leftHeight/2-leftHeight/4+'px',
                        right:leftWidth/2+'px',
                        bottom:leftHeight/2+leftHeight/4+'px',
                        left:leftWidth/2+'px',
                        margin:"auto",
                        position:"absolute"}
                    $(".modal-dialog").css(style);
                }

                function setMove(length){
                    var isMove=false,
                        X= 0,Y=0,
                        leftHeight=window.innerHeight-$(".modal-dialog").eq(length-1).innerHeight(),
                        leftWidth=window.innerWidth-$(".modal-dialog").eq(length-1).innerWidth();
                    position[length-1]={};
                    position[length-1].top=leftHeight/2-leftHeight/4;
                    position[length-1].left=leftWidth/2;
                    position[length-1].bottom=leftHeight/2+leftHeight/4;
                    position[length-1].right=leftWidth/2;

                    function setCss(e){
                        position[length-1].top=position[length-1].top+(e.screenY-Y);
                        position[length-1].left=position[length-1].left+(e.screenX-X);
                        position[length-1].bottom=position[length-1].bottom-(e.screenY-Y);
                        position[length-1].right=position[length-1].right-(e.screenX-X);
                        var clientHeight=$(".modal-dialog").eq(length-1).innerHeight();
                        var style={
                            height:clientHeight+"px",
                            top:position[length-1].top+"px",
                            right:position[length-1].right+"px",
                            bottom:position[length-1].bottom+"px",
                            left:position[length-1].left+"px",
                            margin:"auto",
                            position:"absolute"}
                        $(".modal-dialog").eq(length-1).css(style);
                        X= e.screenX;
                        Y= e.screenY;
                    }
                    $('.modal-header').eq(length-1).on('mousedown',function(e){
                        isMove=true;
                        X= e.screenX;
                        Y= e.screenY;
                        e.preventDefault();
                        e.stopPropagation();
                    });
                    $('.modal-header').eq(length-1).on('mouseup',function(e){
                        if(isMove){
                            isMove=false;
                            setCss(e);
                        }
                        e.preventDefault();
                        e.stopPropagation();
                    });
                    $('.modal-header').eq(length-1).on('mousemove',function(e){
                        if(isMove){
                            setCss(e);
                        }
                        e.preventDefault();
                        e.stopPropagation();
                    })
                }
            }
        },
        bindData:{
            newId:function(){
                return $$id++;
            },
            //将str express转化为function
            parse:function(parseStr){
                var func=new Function('data','return data.'+parseStr+';');
                return func;
            },
            parsefunc:function(parseStr){
                var funcReg=/^(\w+)\((.*)\)/;
                var funcArgs=funcReg.exec(parseStr);
                var funcName=funcArgs[1];
                var args=funcArgs[2].split(',');
                var argStr='';
                for(var i=0;i<args.length;i++){
                    if(!!!args[i]){
                        break;
                    }
                    if(i!==0){
                        argStr=argStr+' ,';
                    }
                    argStr=argStr+'data.'+args[i];
                }
                var func=new Function('data','return data.'+funcName+'('+argStr+')');
                return func;
            },
            bind:function(ele,value){
                for(var i=0;i<ele.length;i++){
                    var tagName=ele[i].tagName;
                    switch (tagName){
                        case'SPAN':
                        case 'P':
                        case 'TD':
                        case 'DIV':
                            ele.eq(i).text(value);
                            break;
                        case 'INPUT':
                            ele.eq(i).val(value);
                            break;
                        default:
                            ele.eq(i).text(value);
                            break;
                    }
                }
            },
            $$directive:[{key:"[ns-repeat]",func:function(){

            },priority:10},{key:"[ns-bind]",func:function(elems,data){
                for(var i=0;i<elems.length;i++){
                    var func=$.bindData.parse(elems.eq(i).attr('ns-bind'));
                    var value=func(data);
                    $.bindData.bind(elems.eq(i),value);
                }
            },priority:0}],
            compileBind:function(ele,data){
                var elems=ele.find('[ns-bind]');
                for(var i=0;i<elems.length;i++){
                    var func=$.bindData.parse(elems.eq(i).attr('ns-bind'));
                    var value;
                    if(elems.eq(i).data().hasOwnProperty('$$nsId')){
                        value=func(elems.eq(i).data());
                    }else{
                        value=func(data);
                    }
                    $.bindData.bind(elems.eq(i),value);
                }
            },
            compileRepeat:function(ele,data){
                ele.find('[ns-repeat].ns-scope').remove();
                var elems=ele.find('[ns-repeat]');
                for(var i=0;i<elems.length;i++){
                    var expre=elems.eq(i).attr('ns-repeat');
                    var args=expre.split(' ');
                    var reData=$.bindData.parse(args[2].replace(/ /g,''))(data);
                    if(!(reData instanceof Array)){
                        return ;
                    }
                    for(var j=0;j<reData.length;j++){
                        data.item=reData[j];
                        data.$index=j;
                        var cloneEle= elems.eq(i).clone(true);
                        data.$$nsId=$.bindData.newId();
                        cloneEle.find('[ns-bind]').data(data);
                        cloneEle.find('[ns-click]').data(data);
                        if(j!==0){
                            cloneEle.addClass("ns-scope");
                        }
                        cloneEle.insertBefore(elems.eq(i));
                    }
                    elems.eq(i).remove();
                }
            },
            compileClick:function(ele,data){
                var elems=ele.find('[ns-click]');
                for(var i=0;i<elems.length;i++){
                    elems.eq(i).off('click');
                    elems.eq(i).on('click',function(e){
                        var func=$.bindData.parsefunc($(this).attr('ns-click'));
                        var thisData=$(this).data();
                        if(thisData.hasOwnProperty('$$nsId')){
                            func(thisData);
                        }else{
                            func(data);
                        }
                    });
                }
            },
            compileAll:function(ele,data){
                $.bindData.compileRepeat(ele,data);
                $.bindData.compileBind(ele,data);
                $.bindData.compileClick(ele,data);
            }
        },
        cookie:{
                //hours为空字符串时,cookie的生存期至浏览器会话结束。hours为数字0时,建立的是一个失效的cookie,这个cookie会覆盖已经建立过的同名、同path的cookie（如果这个cookie存在）。  
                setCookie:function(name,value,hours,path){  
                    var name = escape(name);  
                    var value = escape(value);  
                    var expires = new Date();  
                    expires.setTime(expires.getTime() + hours*3600000);  
                    path = path == "" ? "" : ";path=" + path;  
                    _expires = (typeof hours) == "string" ? "" : ";expires=" + expires.toUTCString();  
                    document.cookie = name + "=" + value + _expires + path;  
                },
                //获取cookie值  
                getCookieValue:function(name){  
                    var name = escape(name);  
                    //读cookie属性，这将返回文档的所有cookie  
                    var allcookies = document.cookie;         
                    //查找名为name的cookie的开始位置  
                    name += "=";  
                    var pos = allcookies.indexOf(name);      
                    //如果找到了具有该名字的cookie，那么提取并使用它的值  
                    if (pos != -1){                                             //如果pos值为-1则说明搜索"version="失败  
                        var start = pos + name.length;                  //cookie值开始的位置  
                        var end = allcookies.indexOf(";",start);        //从cookie值开始的位置起搜索第一个";"的位置,即cookie值结尾的位置  
                        if (end == -1) end = allcookies.length;        //如果end值为-1说明cookie列表里只有一个cookie  
                        var value = allcookies.substring(start,end);  //提取cookie的值  
                        return unescape(value);                           //对它解码        
                        }     
                    else return "";                                             //搜索失败，返回空字符串  
                },
                //删除cookie  
                deleteCookie:function(name,path){  
                    var name = escape(name);  
                    var expires = new Date(0);  
                    path = path == "" ? "" : ";path=" + path;  
                    document.cookie = name + "="+ ";expires=" + expires.toUTCString() + path;  
                }
        }
    });
})();